package com.lxc.service.Impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxc.entity.Authors;
import com.lxc.entity.BusinessException;
import com.lxc.entity.Works;
import com.lxc.mapper.AuthorMapper;
import com.lxc.service.AuthorService;
import com.lxc.util.saveImageToFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class AuthorServiceImpl extends ServiceImpl<AuthorMapper, Authors> implements AuthorService {
    @Autowired
    private AuthorMapper authorMapper;

    @Override
    public Authors getAuthorDetail(Integer id) {
        Authors author = authorMapper.getById(id);
        return author;
    }

    @Override
    public List<Authors> getAllAuthors(Integer pageNum, Integer pageSize) {
        return authorMapper.getAllAuthors(pageNum, pageSize);
    }

    @Override
    public boolean saveAuthor(Authors author, MultipartFile file) throws IOException {


        // 查询是否已存在同名作者
        QueryWrapper<Authors> queryWrapper = new QueryWrapper<>();
        String name = author.getName();
        queryWrapper.eq("name", name);

        if (this.getOne(queryWrapper) != null) {
            throw new BusinessException(400, "作者《" + name + "》已存在");
        }


        if (file != null && !file.isEmpty()) {
            // 1. 文件上传
            String filePath = saveImageToFileSystem.save(file);
            author.setPicture(filePath); // 设置头像路径
        }else {
            throw new BusinessException(500, "请上传图片");
        }



        return authorMapper.insert(author)>0;
    }


    // 实现新增方法：添加作者信息

}